﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace hello_accinv_New_
{
    public partial class DiscountForm : Form
    {
        Decimal unitPrice;

        public DiscountForm()
        {
            InitializeComponent();
        }

        private void txtboxDiscountPercent_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = !(Char.IsDigit(e.KeyChar) || e.KeyChar == '.' || (Keys)e.KeyChar == Keys.Back);
        }

        private void txtboxDiscountBaht_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = !(Char.IsDigit(e.KeyChar) || e.KeyChar == '.' || (Keys)e.KeyChar == Keys.Back);
        }

        private void DiscountForm_Load(object sender, EventArgs e)
        {
            unitPrice = Decimal.Parse(txtboxPrice.Text);
            txtboxDiscountBaht.MaxLength = txtboxPrice.Text.Length;
        }

        private void txtboxDiscountBaht_Leave(object sender, EventArgs e)
        {
            if (txtboxDiscountBaht.Text.Length > 0)
            {
                txtboxDiscountPercent.Text = ((Decimal.Parse(txtboxDiscountBaht.Text) / unitPrice) * 100M).ToString("0");
            }
            else
            {
                txtboxDiscountPercent.Text = "";
            }
        }

        private void txtboxDiscountPercent_TextChanged(object sender, EventArgs e)
        {
            if (txtboxDiscountPercent.Text.Length > 0 && (Int32.Parse(txtboxDiscountPercent.Text) <= 100))
            {
                txtboxDiscountBaht.Text = ((Decimal.Parse(txtboxDiscountPercent.Text) / 100M) * unitPrice).ToString("#,#.00#");
            }
            else
            {
                txtboxDiscountBaht.Text = "";
            }
        }

        private void DiscountForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (DialogResult == System.Windows.Forms.DialogResult.OK)
            {
                if (Decimal.Parse(txtboxDiscountBaht.Text) > 0)
                {
                    txtboxDiscountBaht.Text = Decimal.Parse(txtboxDiscountBaht.Text).ToString("#,#0.00#");
                }
                else if (txtboxDiscountPercent.Text.Length > 0)
                {
                    txtboxDiscountBaht.Text = ((Int32.Parse(txtboxDiscountPercent.Text) / 100) * unitPrice).ToString("#,#.00#");
                }

                if ((txtboxDiscountBaht.Text.Length == 0) ||
                    (Decimal.Parse(txtboxDiscountBaht.Text) == 0) ||
                    (Decimal.Parse(txtboxDiscountBaht.Text) >= unitPrice))
                {
                    MessageBox.Show("Invalid");
                    e.Cancel = true;
                    txtboxDiscountPercent.Focus();
                }
            }
        }
    }
}
